package com.tadpole.music.view.activity.me;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.tadpole.music.R;
import com.tadpole.music.app.MyApplication;
import com.tadpole.music.bean.me.WeChatPayBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.me.WeChatPayIView;
import com.tadpole.music.presenter.me.WeChatPayPresenter;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.question.SimulationExerciseActivity;
import com.tadpole.music.view.activity.question.SimulationPracticeActivity;
import com.tadpole.music.view.event.WeiXinEvent;
import com.tadpole.music.view.widget.PayPopupError;
import com.tadpole.music.view.widget.PayPopupSuccess;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * 支付详情
 * Created By 孙岩
 * on 2020/9/11
 */
public class PayDetailActivity extends BaseActivity implements WeChatPayIView {
    //回退
    private View view_back_icon;
    //标题
    private TextView actionbar_title;
    //购买的课程
    private TextView tvName;
    //金额
    private TextView tvMoney;
    //微信支付
    private TextView tvPay;
    //说明
    private TextView tvDesc;
    //激活码支付
    private TextView tvCodePay;
    //学院id
    private String college_id;
    //goods_id
    private String goods_id;
    //名称（带初级。。）
    private String name;
    //金额
    private String price;
    //名称（不带初级。。）
    private String uname;
    //说明
    private String desc;
    //微信支付
    private WeChatPayPresenter weChatPayPresenter;

    //flag = 1是题库 flag = 2是套题
    private String flag = "0";

    //套题id
    private String suit_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_detail);
        //注册
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


        flag = getIntent().getStringExtra("flag");
        if ("1".equals(flag)) {//题库
            goods_id = getIntent().getStringExtra("goods_id");
            uname = getIntent().getStringExtra("uname");
            college_id = getIntent().getStringExtra("college_id");

        } else if ("2".equals(flag)) {//套题
            suit_id = getIntent().getStringExtra("suit_id");
        }

        name = getIntent().getStringExtra("name");
        price = getIntent().getStringExtra("price");
        desc = getIntent().getStringExtra("desc");

        initViews();
        initListeners();

        weChatPayPresenter = new WeChatPayPresenter();
        weChatPayPresenter.attachView(this);
    }

    //初始化控件
    @SuppressLint("SetTextI18n")
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        actionbar_title = findViewById(R.id.actionbar_title);
        actionbar_title.setText("支付详情");
        tvName = findViewById(R.id.tvName);
        tvName.setText(name);
        tvMoney = findViewById(R.id.tvMoney);
        tvMoney.setText("￥" + price);
        tvPay = findViewById(R.id.tvPay);
        tvCodePay = findViewById(R.id.tvCodePay);
        tvDesc = findViewById(R.id.tvDesc);
        tvDesc.setText(desc);

        if ("1".equals(flag)) {//题库
            tvCodePay.setVisibility(View.VISIBLE);
        } else if ("2".equals(flag)) {//套题
            tvCodePay.setVisibility(View.GONE);
        }
    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                PayDetailActivity.this.finish();
            }
        });

        //微信支付
        tvPay.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    weChatPayPresenter.weChatPay(flag, goods_id, suit_id);
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //激活码支付
        tvCodePay.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    Intent intent = new Intent(PayDetailActivity.this, CodePayActivity.class);
                    intent.putExtra("goods_id", goods_id);
                    startActivityForResult(intent,1000);
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void showWeChatResult(WeChatPayBean.DataBean bean) {
        PayReq req = new PayReq();
        req.appId = bean.getAppid();
        ;//appid
        req.nonceStr = bean.getNoncestr();//随机字符串，不长于32位。推荐随机数生成算法
        req.packageValue = bean.getPackageX();//暂填写固定值Sign=WXPay
        req.sign = bean.getSign();//签名
        req.partnerId = bean.getPartnerid();//微信支付分配的商户号
        req.prepayId = bean.getPrepayid();//微信返回的支付交易会话ID
        req.timeStamp = bean.getTimestamp();//时间戳

        MyApplication.mWxApi.registerApp(bean.getAppid());
        MyApplication.mWxApi.sendReq(req);
    }


    //微信返回
    @Subscribe
    public void onEventMainThread(WeiXinEvent weiXin) {
        if (weiXin.getType() == 3) {//微信支付
            if (weiXin.getErrCode() == BaseResp.ErrCode.ERR_OK) {//成功
                paySuccess();
            } else if (weiXin.getErrCode() == -2) {
                ToastUtils.show("支付取消");
            } else {
                payError();
            }
        }
    }

    //支付成功
    private void paySuccess() {
        final PayPopupSuccess popup = new PayPopupSuccess(PayDetailActivity.this, flag);
        popup.setPopupWindowFullScreen(true);
        popup.showPopupWindow();
        popup.setModeListener(new PayPopupSuccess.IModeSelection() {
            @Override
            public void getMode(int mode) {
                if (mode == 1) {
                    if ("1".equals(flag)) {
                        Intent intent = new Intent(PayDetailActivity.this, SimulationPracticeActivity.class);
                        intent.putExtra("id", Integer.parseInt(college_id));
                        intent.putExtra("name", uname);
                        startActivity(intent);
                    }
                    popup.dismiss();
                    PayDetailActivity.this.finish();
                } else if (mode == 2) {
                    popup.dismiss();
                }
            }
        });
    }

    //支付失败
    private void payError() {
        final PayPopupError popup = new PayPopupError(PayDetailActivity.this);
        popup.setPopupWindowFullScreen(true);
        popup.showPopupWindow();
        popup.setModeListener(new PayPopupError.IModeSelection() {
            @Override
            public void getMode(int mode) {
                if (mode == 1) {
                    popup.dismiss();
                    PayDetailActivity.this.finish();
                } else if (mode == 2) {
                    popup.dismiss();
                } else if (mode == 3) {
                    popup.dismiss();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//取消注册
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1000&&resultCode==1000){
            this.finish();
        }
    }
}
